package com.sunther.document.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sunther.document.Enum.DictEnum;
import com.sunther.document.dao.MsgDao;
import com.sunther.document.entity.MsgEntity;
import com.sunther.document.entity.ProjectEntity;
import com.sunther.document.service.DictService;
import com.sunther.document.service.MsgService;
import com.sunther.document.service.ProjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @author csb
 * @description: TODO
 * @date 2023/6/27 10:47
 */
@Service
public class MsgServiceImpl extends ServiceImpl<MsgDao, MsgEntity> implements MsgService {

    @Autowired
    private DictService dictService;

    @Autowired
    private ProjectService projectService;

    @Override
    public List<MsgEntity> listByKeyword(String keyword, Integer state) {

        QueryWrapper<MsgEntity> wrapper = new QueryWrapper<>();
        if (StrUtil.isNotBlank(keyword)){
            wrapper.like("content",keyword);
        }
        if (null != state){
            wrapper.eq("read_status",state);
        }
        wrapper.orderByDesc("create_time");
        List<MsgEntity> list = list(wrapper);

        getText(list);

        return list;
    }

    @Override
    public void saveMag(Integer type, Integer userId, String nickName, String projectId) {

        ProjectEntity projectEntity = projectService.getById(projectId);

        MsgEntity msgEntity = new MsgEntity();
        msgEntity.setReadStatus(DictEnum.MSG_TYPE_UNREAD.getCode());
        if (type.equals(DictEnum.MSG_CONTENT_ORG.getCode())){
            msgEntity.setContent(projectEntity.getName()+"-"+nickName + DictEnum.MSG_CONTENT_ORG.getName());
        }
        if (type.equals(DictEnum.MSG_CONTENT_TRAN.getCode())){
            msgEntity.setContent(projectEntity.getName()+"-"+nickName + DictEnum.MSG_CONTENT_TRAN.getName());
        }
        msgEntity.init(String.valueOf(userId));
        save(msgEntity);

    }

    @Override
    public void setRead(HttpServletRequest request) {
        QueryWrapper<MsgEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("read_status",DictEnum.MSG_TYPE_UNREAD.getCode());
        List<MsgEntity> list = list(wrapper);
        list.stream().forEach(a -> a.setReadStatus(DictEnum.MSG_TYPE_READ.getCode()));
        updateBatchById(list);
    }

    private void getText(List<MsgEntity> list) {
        if (list != null && list.size() > 0) {
            Map<Integer, String> readStatus = dictService.getMapByType("read_status");
            list.stream().forEach(a -> {
                a.setReadStatusText(readStatus.get(a.getReadStatus()));
            });
        }
    }
}
